﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;
using System.IO;
using System.Net;

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.YouTube;

namespace YoutubeVideoManager
{
    /// <summary>
    /// Logica di interazione per VideoItem.xaml
    /// </summary>
    public partial class VideoItem : UserControl
    {
        #region Events
        public event EventHandler DownloadCompleted;
        #endregion

        #region Properties
        public bool IsDownloading { get; private set; }
        public Video Video { get; private set; }
        public bool IsHD { get; private set; }
        #endregion
        
        #region Fields
        DispatcherTimer clock;
        BackgroundWorker worker;
        int frames;
        List<BitmapImage> thumbnails;
        #endregion
        
        #region Methods
        public VideoItem(Video video)
        {
            InitializeComponent();
            
            this.thumbnails = new List<BitmapImage>();
            this.worker = new BackgroundWorker();

            worker.WorkerSupportsCancellation = worker.WorkerReportsProgress = true;
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

            clock = new DispatcherTimer();
            clock.Interval = TimeSpan.FromMilliseconds(2000);
            this.clock.Tick += new EventHandler(clock_Tick);
            this.clock.Start();

            txtTitle.Text = video.Title;
            txtAuthor.Text = string.Format("di {0}", video.Author);
            txtViewCount.Text = string.Format("{0} visualizzazioni", video.ViewCount);
            txtUpdated.Text = string.Format("caricato {0}", video.Updated.ToShortDateString());
            txtDescr.Text = video.Description;
            Video = video;

            worker.RunWorkerAsync();
        }

        void clock_Tick(object sender, EventArgs e)
        {
            if (IsMouseOver && this.thumbnails.Count > 0)
            {
                DoubleAnimation da = new DoubleAnimation();
                da.From = 1;
                da.To = 0.25;
                da.Duration = new System.Windows.Duration(TimeSpan.FromMilliseconds(500));
                da.AutoReverse = true;
                this.img.BeginAnimation(Image.OpacityProperty, da);
                this.img.Source = this.thumbnails[++this.frames % this.thumbnails.Count];
            }
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            using (WebClient client = new WebClient())
            {
                for (int i = 0; i < Video.Thumbnails.Count; i++)
                {
                    if (worker.CancellationPending)
                        return;
                    byte[] data = client.DownloadData(Video.Thumbnails[i].Url);
                    worker.ReportProgress(0, data);
                }
            }
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            byte[] data = e.UserState as byte[];
            if (data == null)
                return;

            BitmapImage image = new BitmapImage();
            using (MemoryStream ms = new MemoryStream(data))
            {
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = ms;
                image.EndInit();
                image.Freeze();
                if (this.img.Source == null)
                    this.img.Source = image;
            }

            this.thumbnails.Add(image);
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (DownloadCompleted != null)
                DownloadCompleted(this, EventArgs.Empty);
        }
        #endregion
    }
}
